package com.ychs.service;

import com.ychs.dao.RoleMapper;
import com.ychs.entity.Role;
import com.ychs.util.Constants;
import com.ychs.util.DBUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import java.util.List;
import java.util.Map;

/**
 * copyright(c)2021 YYB.ALL rights Reserved
 * <p>
 * 描述:
 *
 * @author 原玉波
 * @version 1.0
 * @date 2021/5/30
 */
public class RoleService implements IBaseService<Role> {
    private Logger logger = Logger.getLogger(this.getClass());

    /**
     * 添加记录
     *
     * @param role 记录对象
     * @return 是否成功
     */
    @Override
    public boolean add(Role role) {
        boolean result = false;
        SqlSession session = DBUtil.getInstance().getSqlSession();
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        result = mapper.insert(role) == Constants.UPDATE_SUCCESS;
        if (result) {
            //如果增加角色成功，再增加对应的权限关系
            mapper.insertRel(role);
        }
        logger.info("************************************ID" + role.getId());
        session.commit();
//        session.close();
        DBUtil.close(session);
        return result;
    }

    /**
     * 修改记录
     *
     * @param role 修改记录对象
     * @return 成功与否
     */
    @Override
    public boolean modify(Role role) {
        boolean result = false;
        SqlSession session = DBUtil.getInstance().getSqlSession();
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        result = mapper.update(role) == Constants.UPDATE_SUCCESS;
        session.commit();
        DBUtil.close(session);
        return result;
    }

    /**
     * 删除记录
     *
     * @param id 待删除记录的主键
     * @return 是否成功
     */
    @Override
    public boolean remove(int id) {

        boolean result = false;
        SqlSession session = DBUtil.getInstance().getSqlSession();
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        result = mapper.delete(id) == Constants.UPDATE_SUCCESS;
        session.commit();
        DBUtil.close(session);
        return result;
    }

    /**
     * 查询单个对象
     *
     * @param id 查询对象的主键
     * @return 查询结果
     */
    @Override
    public Role searchById(int id) {
        Role role = new Role();
        SqlSession session = DBUtil.getInstance().getSqlSession();
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        role = mapper.selectById(id);
        session.commit();
        DBUtil.close(session);
        return role;
    }

    /**
     * 查询多条记录
     *
     * @param conditions 查询条件
     * @return 查询结果
     */
    @Override
    public List<Role> search(Map<String, Object> conditions) {
        SqlSession session = DBUtil.getInstance().getSqlSession();
        RoleMapper mapper = session.getMapper(RoleMapper.class);
        List<Role> roles = mapper.select(conditions);
        session.commit();
        DBUtil.close(session);
        return roles;
    }
}
